import os
import re
import time
import socket
import allure
import cn2an as c2a
from time import strftime
from time import gmtime

from src.log import log
from src.db import MysqlUtil
from src.yaml_util import Yaml
from src.config_util import Config
from conf.setting import BASE_PATH, FILE_PATH


def read_extract(key):
    """前置读取变量"""
    env = Config().get_conf("env")
    try:
        result = Yaml(f"extraction/{env}_extract.yml").read_yml(key)
    except FileNotFoundError:
        raise FileNotFoundError(f"{env}_extract.yml文件不存在，请在extraction包下进行配置")
    with allure.step(f"前置读取变量: {key}, 结果: {result}"):
        log.info(f"前置读取变量: {key}, 结果: {result}")
        return result


def write_extract(key, value):
    """后置保存变量"""
    env = Config().get_conf("env")
    Yaml(f"extraction/{env}_extract.yml").write_yml(key, value)


def ensure_path_sep(path):
    """兼容 windows 和 linux 不同环境的操作系统路径 """
    if "/" in path:
        path = os.sep.join(path.split("/"))

    if "\\" in path:
        path = os.sep.join(path.split("\\"))

    return BASE_PATH + path


def get_all_files(file_path, yaml_data_switch=False) -> list:
    """
    获取文件路径
    :param file_path: 目录路径
    :param yaml_data_switch: 是否过滤文件为 yaml格式， True则过滤
    :return:
    """
    filename = []
    # 获取所有文件下的子文件名称
    for root, dirs, files in os.walk(file_path):
        for _file_path in files:
            path = os.path.join(root, _file_path)
            if yaml_data_switch:
                if 'yaml' in path or '.yml' in path:
                    filename.append(path)
            else:
                filename.append(path)
    return filename


def get_host_ip():
    """
    查询本机ip地址
    :return:
    """
    _s = None
    try:
        _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _s.connect(('8.8.8.8', 80))
        l_host = _s.getsockname()[0]
    finally:
        _s.close()

    return l_host


def now_time():
    """
    获取当前时间, 日期格式: 2021-12-11 12:39:25
    :return:
    """
    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return localtime


def is_digit(string):
    """判断是否为数字字符串"""
    digit_re = re.compile(r'^[-]?[0-9\.]+$')
    return digit_re.search(string)


def open_file_for_upload(filepath):
    """获取文件流，上传文件使用"""
    return open(os.path.join(FILE_PATH, filepath), "rb")


def an2cn(string):
    """阿拉伯数字转中文数字"""
    return c2a.an2cn(string)


def cn2an(string):
    """中文数字转阿拉伯数字"""
    return c2a.cn2an(string)


def exec_sql(sql):
    try:
        mysql = MysqlUtil(**get_env_info().get("mysql"))
        return list(mysql.query_sql(sql).values())[0]
    except Exception:
        raise Exception(f"sql语句: {sql}，sql语句错误或执行异常")


def clean_symbol(text):
    """
    清除字符串特殊符号
    :param text:
    :return:
    """
    return re.sub('[’!"#$`%&\'：|*+～`·,-./:;<=「」>?@，。?★、…—\\\？“”‘’！[\\]^_`{|}~\s]+', "", text)


def get_long_timestamp(int_type=False):
    """
    获取毫秒级时间戳
    :param int_type: 默认返回str类型
    :return:
    """

    if int_type:
        return int(time.time() * 1000)
    return str(int(time.time() * 1000))


def seconds_to_time(seconds):
    return strftime("%H:%M:%S", gmtime(seconds))


class JenkinsUtil(object):

    def __init__(self):
        self.job_name = self.get_info("JOB_NAME")
        self.build_url = self.get_info("BUILD_URL")
        self.build_number = self.get_info("BUILD_NUMBER")
        self.allure_url = f"http://47.94.146.162:9000/job/{self.job_name}/allure/"

    def get_info(self, name, base=''):
        """从Jenkins中获取全局环境变量"""
        return os.getenv(name) and os.getenv(name).strip() or base
